app.controller('caseCtrl', ['$scope', '$http', "commonService","$interval", function($scope, $http, commonService, $interval) {
  $scope.pageConfig = {
          url: "case/list",
          defaultSortOptions: {
            field: "caseOrder",
            direction: "desc"
          },
          columnDefs: [{field: 'caseOrder', displayName: '编号',width: '8%'}, 
                       {field: 'caseName', displayName: '案例名称' ,ellipsis : true}, 
                       {field: 'fileName', displayName: "文件名称",ellipsis : true}, 
                       {field: 'loginCompanyCode', displayName: "登录机构",width: '10%',ellipsis : true}, 
                       {field: 'lastRunTime', displayName: "上次运行",width: '14%',ellipsis : true ,cellFilter: {date: "dateTime"}}, 
                       {field: 'useTimes', displayName: "上次消耗",width: '10%',ellipsis : true, template:'<span ng-if="row.useTimes!=null">{{row.useTimes}}s</span>'}, 
                       {field: 'errorMsg', displayName: "错误原因",ellipsis : true, 
                         template:'<span><i class="icon-camera" ng-if="row.errorImgName!=null" ng-click="showImg(row.errorImgName)"></i>{{row.errorMsg}}</span>'
                       }, 
                       {field: 'status',displayName: "状态",width: '8%',
                         template:'<span ng-if="row.status==1" class="label bg-success">{{$msg("STATUS")[row.status]}}</span>'
                         +'<span ng-if="row.status==3" class="label bg-danger">{{$msg("STATUS")[row.status]}}</span>' 
                         +'<span ng-if="row.status==2|| row.status==4" class="label bg-primary">{{$msg("STATUS")[row.status]}}</span>' 
                       }
                       ],
          selectStyle : "checkbox",
          pagination : true,
          data : "caseList",
          dataKey : "uuid"
  }
  
  $scope.isQuery = false;
  $scope.onAdd = onAdd;
  $scope.onAfter = onAfter;
  $scope.deleteCase = deleteCase;
  $scope.updateCase = updateCase;
  $scope.runCase = runCase;
  $scope.monitorCase = monitorCase;
  $scope.showImg = showImg;
  $scope.refreshCase = refreshCase;
  $scope.stopCase = stopCase;
  $scope.openQueryCase = openQueryCase;
  $scope.searchCriteria = {};
  function openQueryCase(){
    layer.open({
      type: 1,
      title : '筛选案例',
      btn: ['确认'],
      area: ['600px', '300px'],
      content: $('#queryCaseId'),
      anim: -1,
      isOutAnim: false,
      resize: true,
      scrollbar: false,
      yes: function(index, layero){
              layer.close(index);
              if(!isEmptyObj($scope.searchCriteria,"limit,page,orderByClause,orderBy")){
                $scope.isQuery = true;
              }else{
                $scope.isQuery = false;
              }
              $scope.$apply();
              $scope.pageConfig.refresh(true);
      }
    });
  }
  function showImg(imageFileName){
    layer.open({
      type: 2,
      title: '浏览器截屏',
      shadeClose: true,
      shade: 0.8,
      area: ['1000px', '500px'],
      content: 'case/errorImg?imageFileName='+imageFileName 
    }); 
  }
  function isEmptyObj(obj,ignoreStr){
    if(obj != null){
      for(var o in obj){
        var check = true;
        if(ignoreStr){
          if(ignoreStr.indexOf(o) != -1){
            check = false
          }
        }
        if(check && !angular.isEmpty(obj[o])){
           return false;
           break;
        }
      }
    }
    return true;
  }
  function onAdd(file, up, up_pargs) {
    var name = file.name;
    if ((name.lastIndexOf(".xml") == -1)) {
      layer.msg("只支持xml的案例!");
      return;
    }
    up.start();
  }
  function onAfter(file, data, up, up_pargs) {
    if(data.success){
      layer.msg("上传案例成功!");
      $scope.pageConfig.refresh();
    }else{
      layer.msg(data.errorMsg);
    }
  }
  
  function deleteCase() {
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length <= 0) {
      layer.msg("请选择一条记录");
      return;
    }
    layer.confirm('确认删除？', {
      btn: ['确定', '取消']
    }, function() {
        var keys = [];
        for(var i = 0;i < selectItems.length; i++){
          keys.push(selectItems[i].uuid);
        }
        commonService.post('case/delete', keys).then(function(response) {
          layer.msg("删除成功!");
          $scope.pageConfig.clearSelectItems(keys);
          $scope.pageConfig.refresh();
        });
    });
  }
  
  function updateCase() {
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length != 1) {
      layer.msg("请选择一条记录,不可以选择多条记录");
      return;
    }
    commonService.post('case/query', {"uuid":selectItems[0].uuid}).then(function(response) {
      $('#updateCaseId').val(response.data);
      layer.open({
        type: 1,
        title : '修改case',
        btn: ['确认'],
        area: ['1000px', '500px'],
        content: $('#updateCaseId'),
        anim: -1,
        isOutAnim: false,
        resize: true,
        scrollbar: false,
        yes: function(index, layero){
              commonService.post('case/update', {
                "uuid": selectItems[0].uuid,
                "xml": $('#updateCaseId').val()
              }).then(function(response) {
                layer.msg("更新成功!");
                layer.close(index);
                $scope.pageConfig.clearSelectItems();
                $scope.pageConfig.refresh();
              });
        }
      });
    });
   }
  
  function runCase(){
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length <= 0) {
      layer.msg("请选择一条记录");
      return;
    }
    var keys = [];
    for(var i = 0;i < selectItems.length; i++){
      keys.push(selectItems[i].uuid);
      if(selectItems[i].status == "2"){
        layer.msg("不能包含正在运行的案例");
      }
    }
    layer.confirm('确定运行？', {
      btn: ['确定', '取消']
    }, function() {
        commonService.post('case/run', keys).then(function(response) {
          layer.msg("运行成功!刷新查看状态");
          $scope.pageConfig.clearSelectItems();
          $scope.pageConfig.refresh();
        });
    });
  }
  
  function monitorCase(){
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length <= 0) {
      layer.msg("请选择一条记录");
      return;
    }
    var tabs = [];
    var keys = [];
    for(var i = 0;i < selectItems.length; i++){
      keys.push(selectItems[i].uuid);
      tabs.push({"title":selectItems[i].caseName,"content":"loading...","uuid":selectItems[i].uuid})
      tabs[0].active = true;
    }
    $scope.tabs = tabs;
    var intervalIndex = $interval(function(){
      commonService.post('case/queryRunInfo', keys).then(function(response) {
        var itemList= response.data;
        if(itemList){
          $.each(itemList , function(i){
            for(var i= 0;i < tabs.length;i++){
               if(tabs[i].uuid == itemList[i].uuid){
                  tabs[i].stepInfos= itemList[i].stepInfos;
                  tabs[i].errorMsg = itemList[i].errorMsg;
               }
            }
          });
        }
      });
    },2000);
    layer.open({
      type: 1,
      title : '监控台',
      area: ['1000px', '500px'],
      content: $('#monitorId'),
      anim: -1,
      isOutAnim: false,
      resize: true,
      scrollbar: false,
      cancel: function(index, layero){ 
          layer.close(index)
          $interval.cancel(intervalIndex);
          $scope.pageConfig.clearSelectItems();
          $scope.pageConfig.refresh();
        return false; 
      } 
    });
  }
  
  function refreshCase(){
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length <= 0) {
      layer.msg("请选择一条记录");
      return;
    }
    var keys = [];
    for(var i = 0;i < selectItems.length; i++){
      keys.push(selectItems[i].uuid);
      if(selectItems[i].status == "2"){
        layer.msg("不能包含正在运行的案例");
      }
    }
    layer.confirm('确定刷新？', {
      btn: ['确定', '取消']
    }, function() {
        commonService.post('case/refresh', keys).then(function(response) {
          layer.msg("刷新成功!");
          $scope.pageConfig.clearSelectItems();
          $scope.pageConfig.refresh();
        });
    });
  }
  function stopCase(){
    var selectItems = $scope.pageConfig.getSelectItems();
    if (selectItems == null || selectItems.length <= 0) {
      layer.msg("请选择一条记录");
      return;
    }
    var keys = [];
    for(var i = 0;i < selectItems.length; i++){
      keys.push(selectItems[i].uuid);
      if(selectItems[i].status == "1"||selectItems[i].status == "3"){
        layer.msg("不能包含没有运行的案例");
      }
    }
    layer.confirm('确定强制结束？', {
      btn: ['确定', '取消']
    }, function() {
      commonService.post('case/stop', keys).then(function(response) {
        layer.msg("强制结束操作成功,等待案例结束!");
        $scope.pageConfig.clearSelectItems();
        $scope.pageConfig.refresh();
      });
    });
  }
  
  
  
  
}]);